<template>
  <div>
    <div>
      <TWXVnc-component
        :thingName="thingName"
        :tunnelName="tunnelName"
        :vncPassword="vncPassword"
        :host="host"
        :port="port"
        :cookieUrl="cookieUrl"
        :userName="userName"
        :passWord="passWord"
      ></TWXVnc-component>
    </div>
    <div>
      <button @click="createAppKey">create key</button>
    </div>
    <div>
      <button @click="deleteAppKey">Delete key</button>
    </div>
    <div>
      <button @click="createUser">create User</button>
    </div>
    <div>
      <button @click="getUserExtensions">Set Email</button>
    </div>
    <div>
      <button @click="deleteAPP">deleteAPP</button>
    </div>
    <div>
      <button @click="getCsvFile">Get CSV</button>
    </div>
    <div>
      <p class="exp"><a
          @click="exportData"
          id="ex"
        >Export</a></p>
    </div>
    <div class="tab-excel">
      <!-- 设置border="1"以显示表格框线 -->
      <table
        id="ex-tab"
        border="1"
        style="text-align: center;"
      >
        <!-- caption元素可以生成表标题，其单元格列跨度为表格的列数 -->
        <caption>export CSV file</caption>
        <thead>
          <tr>
            <th>Serial number</th>
            <th>value</th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="(item, index) in csvData"
            :key="index"
          >
            <td>{{ index + 1 }}</td>
            <td>{{ item }}</td>
          </tr>
        </tbody>
      </table>
    </div>
    <div class="box">
      <i><span></span></i>
    </div>
  </div>
</template>

<script>
import axios from "../service/common-service/service";
import TWXVncComponent from "../common/vncComponent/TWXVncComponent";
export default {
  data() {
    return {
      thingName: "test",
      tunnelName: "vnc",
      vncPassword: 123456,
      host: "http://192.168.70.67",
      port: "8080",
      userName: "Administrator",
      passWord: "1234567890kong",
      cookieUrl:
        "http://127.0.0.1:8080/Thingworx/Resources/CurrentSessionInfo/Services/GetCurrentUserLanguage",
      csvData: ["a", "b", "c", "d", "e", "f", "g"],
      data1: [
        // 'test1', 'test2', 'test3'
        { name: "test1" },
        { name: "test2" },
        { name: "test3" }
      ]
    };
  },
  components: {
    TWXVncComponent
  },
  created() {
    let farmId = this.$route.query.farmId;
    console.log(farmId)
  },
  methods: {
    createUser() {
      let url = `/api/Thingworx/Users`;
      let param = {
        // PersistentValues: {},
        // aspects: {},
        // avatar: "",
        configurationTables: {
          Settings: {
            dataShape: {
              description: "",
              fieldDefinitions: {
                language: {
                  aspects: { defaultValue: "" },
                  baseType: "STRING",
                  description: "Primary Language",
                  name: "language",
                  ordinal: 0
                }
              },
              name: ""
            },
            description: "",
            isMultiRow: false,
            name: "Settings",
            rows: [{ language: "" }]
          },
          UserExtensions: {
            dataShape: {
              description: "User extension properties",
              name: "UserExtensions",
              fieldDefinitions: {}
            },
            description: "",
            isMultiRow: false,
            name: "UserExtensions",
            rows: []
          }
        },
        // description: "",
        // designTimePermissions: {Update: [], Create: [], Read: [], Metadata: [], Delete: []},
        // documentationContent: "",
        enabled: "true",
        // guid: "",
        // homeMashup: "",
        // language: "",
        // lastModifiedDate: 0,
        // location: {elevation: 0, longitude: 0, latitude: 0, units: "WGS84"},
        // mobileMashup: "",
        name: "TestUser",
        password: "",
        plainTextPassword: "1234567890kong",
        projectName: "GEHC.DCAR.FM",
        runTimePermissions: { permissions: [] },
        tags: []
      };
      axios.put(url, param).then(res => {
        if (res) {
          console.log(res);
        }
      });
    },
    getUserExtensions() {
      let url = "/api/Thingworx/Users/TestUser";
      let t = new Date().getTime();
      let param = {
        ts: t
      };
      axios.get(url, param).then(res => {
        if (res) {
          this.setUserEmail(res["data"]);
        }
      });
    },
    setUserEmail(data) {
      let url =
        "/api/Thingworx/Users/TestUser?reason=user-extensions%" +
        "20%3A%" +
        "20emailAddress%" +
        "20%3A%" +
        "20updated" +
        "%0A";
      data["configurationTables"]["UserExtensions"]["rows"][9]["value"] =
        "Administrator@thingworx.com";
      axios.put(url, data).then(res => {
        if (res) {
          console.log(res);
        }
      });
    },
    deleteUser() {
      let url = `/api/Thingworx/Users/TestUser`;
      axios.delete(url).then(res => {
        if (res) {
          console.log(res);
        }
      });
    },
    createAppKey() {
      let url = `/api/Thingworx/ApplicationKeys`;
      let param = {
        // avatar: "",
        clientName: "",
        description: "",
        designTimePermissions: { Create: [], Update: [], Delete: [], Read: [] },
        entityType: "ApplicationKeys",
        // homeMashup: "",
        id: "",
        // ipWhitelist: "",
        isSystemObject: false,
        name: "TestKey",
        runTimePermissions: { permissions: [] },
        tags: [],
        userNameReference: "Administrator"
      };
      axios.put(url, param).then(res => {
        if (res) {
          console.log(res);
        }
      });
    },
    deleteAppKey() {
      let url = `/api/Thingworx/ApplicationKeys/TestKey`;
      axios.delete(url).then(res => {
        if (res) {
          console.log(res);
        }
      });
    },
    deleteAPP() {
       axios
        .post("/api/Thingworx/Things/b43a95b7-0788-449b-9419-f0f4cb627b0b_AutomationTestHardwareToken_0009/Services/Unattach", {
          "AppId": 2
        })
        .then(res => {
          console.log(res);
        });
    },
    getCsvFile() {
      let ts = new Date().getTime();
      let url = `/api/Thingworx/Things/GEHC.CORE.FM.AuditLogsUtil/Services/GetDigitalTwinAuditCSV?ts=${ts}`;
      const param = {
        RiskLevel: "Low"
      };
      axios.post(url, param).then(res => {
        if (res) {
          var a = res["data"]["rows"][0]["array_agg"];
          var b = this.csvJSON(a);
          console.log(b);
        }
      });
    },
    csvJSON(csv) {
      console.log(csv);
      var lines = csv.split("\n");
      var result = [];
      var headers = lines[0].split(",");
      for (var i = 1; i < lines.length; i++) {
        var obj = {};
        var currentline = lines[i].split(",");
        for (var j = 0; j < headers.length; j++) {
          obj[headers[j]] = currentline[j];
        }
        result.push(obj);
      }
      //return result; //JavaScript object
      return JSON.stringify(result); //JSON
    },
    exportData() {
      /* // 使用outerHTML属性获取整个table元素的HTML代码（包括<table>标签），然后包装成一个完整的HTML文档，设置charset为urf-8以防止中文乱码
        var html = "<html><head><meta charset='utf-8' /></head><body>" + document.getElementById("ex-tab").outerHTML + "</body></html>";
        // 实例化一个Blob对象，其构造函数的第一个参数是包含文件内容的数组，第二个参数是包含文件类型属性的对象
        var blob = new Blob([html], { type: "application/vnd.ms-excel" });
        // var a = document.getElementsByTagName("a")[0];
        // 利用URL.createObjectURL()方法为a元素生成blob URL
        var href = URL.createObjectURL(blob);
        document.getElementById("ex").setAttribute("href", href);
        
        // // 设置文件名，目前只有Chrome和FireFox支持此属性
        document.getElementById("ex").setAttribute("download","data.xls");
        // a.download = "实际功率曲线.xls";
        // a.click();
        // document.getElementById("ex").click(); */
      this.export2CSVFile(this.data1, "export-file", false);
    },
    export2CSVFile(JSONData, ReportTitle, ShowLabel) {
      console.log(JSONData);
      // If JSONData is not an object then JSON.parse will parse the JSON string in an Object
      const arrData =
        typeof JSONData !== "object" ? JSON.parse(JSONData) : JSONData;
      let CSV = "";
      // Set Report title in first row or line
      CSV += `${ReportTitle}\r\n`;
      // This condition will generate the Label/Header
      if (ShowLabel) {
        let row = "";
        // This loop will extract the label from 1st index of on array
        for (let index in arrData[0]) {
          // Now convert each value to string and comma-seprated
          row += `${index},`;
        }
        row = row.slice(0, -1);
        // append Label row with line break
        CSV += `${row}\r\n`;
      }
      // 1st loop is to extract each row
      for (let i = 0; i < arrData.length; i++) {
        let row = "";
        // 2nd loop will extract each column and convert it in string comma-seprated
        for (let key in arrData[i]) {
          row += `${arrData[i][key]},`;
        }
        // if the JSONData just has string data
        // row += `${arrData[i]},`
        row.slice(0, row.length - 1);
        // add a line break after each row
        CSV += `${row}\r\n`;
      }

      if (CSV === "") {
        return;
      }
      // Generate a file name
      let fileName = "MyReport_";
      // this will remove the blank-spaces from the title and replace it with an underscore
      fileName += ReportTitle.replace(/ /g, "_");
      // Initialize file format you want csv or xls
      const uri = `data:text/csv;charset=utf-8,${escape(CSV)}`;
      // Now the little tricky part.
      // you can use either>> window.open(uri);
      // but this will not work in some browsers
      // or you will not get the correct file extension
      // this trick will generate a temp <a /> tag
      const link = document.createElement("a");
      link.href = uri;

      // set the visibility hidden so it will not effect on your web-layout
      link.style = "visibility:hidden";
      link.download = `${fileName}.csv`;

      // this part will append the anchor tag and remove it after automatic click
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }
};
</script>
<style scoped>
.exp {
  margin: 0;
  display: inline-block;
  width: 100px;
  height: 20px;
  padding: 5px;
  background: red;
  border-radius: 5px;
  text-align: center;
  vertical-align: top;
}

.box {
  position: relative;
  width: 300px;
  height: 300px;
  border: 5px solid deepskyblue;
  border-radius: 50%;
}

.box i {
  display: block;
  width: 300px;
  height: 300px;
  position: absolute;
  left: -10px;
  top: -10px;
  border-radius: 50%;
  border: 10px solid transparent;
  /*旋转*/
  animation: circleRoate 10s;
  animation-timing-function: linear;
  animation-iteration-count: infinite
}

.box i span {
  position: absolute;
  left: 239px;
  top: 24px;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: dodgerblue;
}

@keyframes circleRoate {
  from {transform: rotate(0deg) infinite;}
  to {transform: rotate(360deg);}
}
</style>